package com.nttuan.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.nfc.Tag;
import android.util.Log;

import com.nttuan.model.entity.Category;
import com.nttuan.model.entity.Contact;
import com.nttuan.model.entity.Location;
import com.nttuan.model.entity.Notification;
import com.nttuan.model.entity.Task;
import com.nttuan.model.entity.Track;
import com.nttuan.model.entity.User;

public class JSONParser {
    private static final String TAG = "JSONParser";
//    private static final String BASE_URL = "http://10.0.3.2/calender";
    private static final String BASE_URL = "http://quachhoang.com/calendar";

    public static JSONObject sendDelete(Track track){
        Net netSupport = new Net();
        String url =BASE_URL+ "/action.php";
        try{
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("action", Track.ACTION_DELETE_INVITE));
            params.add(new BasicNameValuePair(Task.PUBLIC_ID, track.getTask().getPublicId()+""));
            params.add(new BasicNameValuePair(Track.MESSAGE, track.getMessage()));
            return netSupport.makeHttpRequest(url,"GET", params);
        }catch (Exception e){
            Log.d(TAG, "sendDelete:" + e.toString());
            return null;
        }
    }
    public static boolean register(User user){
        String url =BASE_URL+ "/register.php";
        Net netSupport = new Net();
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(User.USER_NAME, user.getUserName()));
            params.add(new BasicNameValuePair(User.EMAIL, user.getEmail()));
            params.add(new BasicNameValuePair(User.PHONE, user.getPhone()));
            params.add(new BasicNameValuePair(User.ADDRESS, user.getAddress()));
            params.add(new BasicNameValuePair(User.FACEBOOK, user.getFacebook()));
            params.add(new BasicNameValuePair(User.SKYPE, user.getSkype()));
            JSONObject root = netSupport.makeHttpRequest(url, "GET", params);
            if(root.getString("result").equals("1"))
                return true;
            return false;
        }catch (Exception e) {
            Log.d(TAG, "register:" + e.toString());
            return false;
        }
    }
    public static String currentTimeServer(){
        String url =BASE_URL+ "/support.php";
        Net netSupport = new Net();
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            JSONObject root = netSupport.makeHttpRequest(url, "GET", params);
            if(root.getString("result").equals("1"))
                return root.getString("now");
        }catch (Exception e){
            Log.d(TAG,"currentTimeServer:"+ e.toString());
            return null;
        }
        return null;
    }
    public static JSONObject sendAcceptInvite(String email, int publicId){
        Net netSupport = new Net();
        Log.d(TAG, "sendAcceptInvite: start");
        String url =BASE_URL+ "/action.php";
        try{
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("action", Track.ACTION_SEND_ACCEPT));
            params.add(new BasicNameValuePair(Task.PUBLIC_ID, publicId+""));
            params.add(new BasicNameValuePair(User.EMAIL, email));
            return netSupport.makeHttpRequest(url,"GET", params);
        }catch (Exception e){
            Log.d(TAG, "sendAcceptInvite:" + e.toString());
            return null;
        }
    }
    public static JSONObject sendTask(Task task,String action, String message){
        Net netSupport = new Net();
        Log.d(TAG, "sendTask: start");
        String url =BASE_URL+ "/action.php";
        try{
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("action", action));
            params.add(new BasicNameValuePair(Track.MESSAGE, message));
//            put task data
          //params.add(new BasicNameValuePair(Task.PUBLIC_ID,task.getPublicId()+""));
            params.add(new BasicNameValuePair(Task.TASK_ID,task.getTaskId()+""));
            params.add(new BasicNameValuePair(Task.PUBLIC_ID,task.getPublicId()+""));
            params.add(new BasicNameValuePair(Task.TASK_NAME,task.getTaskName()));
            params.add(new BasicNameValuePair(Task.DATE_START,Support.toString(task.getStart())));
            params.add(new BasicNameValuePair(Task.DATE_END,Support.toString(task.getEnd())));
            params.add(new BasicNameValuePair(Task.DURING,task.getDuring()+""));
            params.add(new BasicNameValuePair(Task.REMIND,task.getRemind()+""));
            params.add(new BasicNameValuePair(Task.LEVEL,task.getLevel()+""));
            params.add(new BasicNameValuePair(Task.REPEAT,task.getRepeat()));
          //params.add(new BasicNameValuePair(Task.NOTE,task.getNote()));
            params.add(new BasicNameValuePair(Task.TIME_ZONE,task.getTimeZone()));
//            put location
            Location loc = task.getLocation();
            params.add(new BasicNameValuePair(Location.ADDRESS,loc.getAddress()));
            params.add(new BasicNameValuePair(Location.LOG_LAG,loc.getLog_lag()));
          //params.add(new BasicNameValuePair(Location.NOTE,loc.getNote()));
//            put category
            Category cat = task.getCategory();
            params.add(new BasicNameValuePair(Category.CATEGORY_NAME,cat.getCategoryName()));
            params.add(new BasicNameValuePair(Category.CATEGORY_ICON,cat.getCategoryIcon()));
         // params.add(new BasicNameValuePair(Category.NOTE,cat.getNote()));
//            put contact
            JSONObject jContacts = new JSONObject();
            JSONArray array = new JSONArray();
            JSONObject jContact;
            StringBuilder contacts = new StringBuilder();
            if(task.getListContact() != null){
                for(Contact contact : task.getListContact()){
                    contacts.append(contact.getUser().getEmail()+":");
                    contacts.append(contact.isLeader()? "1:":"0:");
                    contacts.append(contact.isAttend()? "1<sp>":"0<sp>");
                }
            }
            Log.d("contacts", contacts.toString());
            params.add(new BasicNameValuePair("contacts",contacts.toString()));
            return netSupport.makeHttpRequest(url,"GET", params);
        }catch (Exception e){
            Log.d(TAG,"sendTask:"+ e.toString());
            return null;
        }
    }
    public static Task getTask(int publicId, String action){
        Task task = null;
        String url =BASE_URL+ "/get-action.php";
        Net netSupport = new Net();
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("public_id",publicId+""));
            params.add(new BasicNameValuePair("action",action));
            JSONObject rootObject = netSupport.makeHttpRequest(url,"GET",params);
            int result = rootObject.getInt("result");
            if(result == 0)
                return null;
            task = new Task();
            JSONObject obj = rootObject.getJSONObject(Task.TABLE_NAME);
            task.setPublicId(obj.getInt(Task.PUBLIC_ID));
            task.setTaskId(obj.getInt(Task.TASK_ID));
            task.setTaskName(obj.getString(Task.TASK_NAME));
            task.setStart(Support.toDateTime(obj.getString(Task.DATE_START), false));
            task.setEnd(Support.toDateTime(obj.getString(Task.DATE_END), false));
            task.setDuring(obj.getInt(Task.DURING));
            task.setRemind(obj.getInt(Task.REMIND));
            task.setLevel(obj.getInt(Task.LEVEL));
            task.setRepeat(obj.getString(Task.REPEAT));
            task.setNote(obj.getString(Task.NOTE));
            task.setTimeZone(obj.getString(Task.TIME_ZONE));
            task.setActive(false);

            obj = rootObject.getJSONObject(Location.TABLE_NAME);
            Location location = new Location();
            location.setAddress(obj.getString(Location.ADDRESS));
            location.setLog_lag(obj.getString(Location.LOG_LAG));
            location.setNote(obj.getString(Location.NOTE));
            location.setActive(true);
            task.setLocation(location);

            obj = rootObject.getJSONObject(Category.TABLE_NAME);
            Category category = new Category();
            category.setCategoryName(obj.getString(Category.CATEGORY_NAME));
            category.setCategoryIcon(obj.getString(Category.CATEGORY_ICON));
            category.setNote(obj.getString(Category.NOTE));
            category.setActive(true);
            task.setCategory(category);

            List<Contact> contacts = new ArrayList<Contact>();
            JSONArray jContacts = rootObject.getJSONArray("contacts");
            JSONObject jContact;
            Contact contact;
            JSONObject jUser;
            User user;
            for(int i = 0; i< jContacts.length(); i++){
                jContact = jContacts.getJSONObject(i);
                contact = new Contact();
                contact.setAttend(Support.toBoolean(jContact.getInt(Contact.ATTEND)));
                contact.setLeader(Support.toBoolean(jContact.getInt(Contact.LEADER)));
                contact.setActive(true);
                jUser = jContact.getJSONObject(User.TABLE_NAME);
                user = new User();
                user.setUserName(jUser.getString(User.USER_NAME));
                user.setEmail(jUser.getString(User.EMAIL));

                user.setAddress(jUser.getString(User.ADDRESS));
                user.setPhone(jUser.getString(User.PHONE));
                user.setFacebook(jUser.getString(User.FACEBOOK));
                user.setSkype(jUser.getString(User.SKYPE));
                user.setActive(true);
                contact.setUser(user);
                contacts.add(contact);
            }

            task.setListContact(contacts);
        }catch (Exception e){
            Log.d(TAG,"getTask:"+ e.toString());
            return null;
        }
        return task;
    }
    public static List<User> findUser(String key){
        String url =BASE_URL+ "/find-user.php";
        List<User> list = new ArrayList<User>();
        Net netSupport = new Net();
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("key",key));
            JSONObject root = netSupport.makeHttpRequest(url, "GET", params);
            int result = root.getInt("result");
            if(result == 0)
                return list;
            JSONArray users = root.getJSONArray("users");
            JSONObject item;
            User user;
            for(int i=0; i < users.length(); i++) {
                item = users.getJSONObject(i);
                user = new User();
                user.setUserName(item.getString(User.USER_NAME));
                user.setEmail(item.getString(User.EMAIL));
                user.setAddress(item.getString(User.ADDRESS));
                user.setPhone(item.getString(User.PHONE));
                user.setFacebook(item.getString(User.FACEBOOK));
                user.setSkype(item.getString(User.SKYPE));
                user.setActive(true);
                list.add(user);
            }
        }catch (Exception e){
            Log.d(TAG, "findUser:" +e.toString());
        }
        return list;
    }
    public static List<Notification> getNotification(String email, String slastTime){
        String url =BASE_URL+ "/notification.php";
        List<Notification> list = new ArrayList<Notification>();
        Net netSupport = new Net();
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("email",email));
            params.add(new BasicNameValuePair("last_update",slastTime)); //---------------------------------
            JSONObject rooObject = netSupport.makeHttpRequest(url,"GET",params);
            int result = rooObject.getInt("result");
            if(result == 0)
                return list;
            JSONArray actions = rooObject.getJSONArray("actions");
            Notification notificationItem;
            JSONObject item;
            for(int i=0; i < actions.length(); i++){
                item = actions.getJSONObject(i);
                notificationItem = new Notification();
                notificationItem.setPublicId(item.getInt("publicId"));
                notificationItem.setAction(item.getString("action"));
                notificationItem.setMessage(item.getString("message"));
                StringBuilder lastTime = new StringBuilder();
                lastTime.append(item.getString("lastTime")+".000");
                notificationItem.setLastTime(Support.toDateTimeMili(lastTime.toString()));
                list.add(notificationItem);
            }
        }catch (Exception e){
            Log.d(TAG,"getNotification:"+ e.toString());
            return list;
        }
        return  list;
    }
}
